package com.example.endproject;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;
import androidx.recyclerview.widget.RecyclerView;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ManagerActivity extends AppCompatActivity implements AdapterView.OnItemLongClickListener{
    private static final String TAG = "ManagerActivity";
    DBHelper dbHelper;
    SQLiteDatabase mSqlDB;
    List<HashMap<String,String>> items;
    ListView listView;
    int tempPosition;
    SimpleAdapter listAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manager);
        items = new ArrayList<>();
        listView = findViewById(R.id.listview_manager);
        dbHelper = new DBHelper(this);
        mSqlDB = dbHelper.getWritableDatabase();
        String sql = "select a.user_name,a.pwd,c.ID,c.name from "+DBHelper.TB_NAME_USER+" a,"+DBHelper.TB_NAME_Relate+" b,"+DBHelper.TB_NAME_MSG+" c"
                +" where a.user_name = b.user_name AND b.ID = c.ID";
        Cursor cursor = mSqlDB.rawQuery(sql, null);
        if (!cursor.moveToFirst()){
            Log.i(TAG, "onCreate: 没有数据");
            return;
        }
        for (int i =0;i<cursor.getCount();i++){
            HashMap<String,String> map = new HashMap<>();
            map.put("user_name",cursor.getString(cursor.getColumnIndexOrThrow("user_name")));
            map.put("pwd",cursor.getString(cursor.getColumnIndexOrThrow("pwd")));
            map.put("ID",cursor.getString(cursor.getColumnIndexOrThrow("ID")));
            map.put("name",cursor.getString(cursor.getColumnIndexOrThrow("name")));
            items.add(map);
            cursor.moveToNext();
        }

        listAdapter = new SimpleAdapter(this,items, R.layout.activity_item,
                new String[]{"user_name","pwd","ID","name"},
                new int[]{R.id.item_userName,R.id.item_pwd,R.id.item_ID,R.id.item_Name});
        listView.setAdapter(listAdapter);
        listView.setEmptyView(findViewById(R.id.no_data));
        listView.setOnItemLongClickListener(this);
        cursor.close();
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        //Toast.makeText(getApplicationContext(), "进入成功", Toast.LENGTH_SHORT).show();
        tempPosition = position;
        Object itemAtPosition = listView.getItemAtPosition(position);
        HashMap<String, String> itemMap = (HashMap<String, String>) itemAtPosition;//当前选定列的位置对应的listItem
        PopupMenu popupMenu = new PopupMenu(this, view);
        popupMenu.getMenuInflater().inflate(R.menu.manager_menu, popupMenu.getMenu());
        popupMenu.show();
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.update:
                        Log.i(TAG, "onMenuItemClick: 管理员点击了更新");
                        Intent intent = new Intent(ManagerActivity.this, ManagerUpdateActivity.class);
                        intent.putExtra("user_name", itemMap.get("user_name"));
                        intent.putExtra("pwd", itemMap.get("pwd"));
                        intent.putExtra("ID", itemMap.get("ID"));
                        Log.i(TAG, "onMenuItemClick: 传递过去的值为:" + itemMap.get("user_name"));
                        startActivityForResult(intent, 1000);
                        break;
                    case R.id.delete:
                        Log.i(TAG, "onMenuItemClick: 管理员点击了删除");
                        AlertDialog.Builder builder = new AlertDialog.Builder(ManagerActivity.this);
                        builder.setTitle("提示").setMessage("是否删除该用户数据").setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                items.remove(position);
                                listAdapter.notifyDataSetChanged();
                                try {
                                    mSqlDB.beginTransaction();
                                    mSqlDB.delete(DBHelper.TB_NAME_USER,"user_name = ?",new String[]{itemMap.get("user_name")});
                                    mSqlDB.delete(DBHelper.TB_NAME_MSG,"ID = ?",new String[]{itemMap.get("ID")});
                                    mSqlDB.delete(DBHelper.TB_NAME_Relate,"user_name = ?",new String[]{itemMap.get("user_name")});
                                    mSqlDB.setTransactionSuccessful();
                                }catch (SQLException e){
                                    Log.i(TAG, "onClick: 管理员删除出错");
                                }
                                finally {
                                    mSqlDB.endTransaction();
                                }
                            }
                        }).setNegativeButton("否",null);
                        builder.create().show();
                        break;
                }
                return true;
            }
        });
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1000 && resultCode ==2000){
            if (data != null) {
                HashMap<String,String> map = new HashMap<>();
                map.put("user_name",data.getStringExtra("user_name2"));
                map.put("pwd",data.getStringExtra("pwd2"));
                map.put("ID",data.getStringExtra("ID2"));
                map.put("name",data.getStringExtra("name2"));
                items.set(tempPosition,map);
                listAdapter.notifyDataSetChanged();
            }
        }


    }
}